package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.entity.SkuCategory;
import com.example.springstudy.service.SkuCategoryService;
import com.example.springstudy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/api/category")
public class SkuCategoryController {
    @Autowired
    SkuCategoryService skuCategoryService;

    @GetMapping("/list")
    public Result<?> list(){
        return Result.success(skuCategoryService.listAll());
    }

    @SaveLog("添加商品类目")
    @PostMapping("/add")
    public Result<?> add(@RequestBody SkuCategory category){
        try{
            Assert.hasText(category.getName(), "item name is empty");
            if(category.getId() == null || category.getId() == 0){
                category.setCreateTime(DateUtils.defaultDate());
            } else {
                category.setUpdateTime(DateUtils.defaultDate());
            }
            return Result.success(skuCategoryService.addCategory(category));
        } catch (Exception e){
            return Result.failed(e.getMessage());
        }
    }

    @SaveLog("修改商品类目")
    @PostMapping("/update")
    public Result<?> update(@RequestBody SkuCategory category){
        try{
            Assert.isTrue(category.getId()!=null&&category.getId()!=0, "id is empty");
            Assert.hasText(category.getName(), "item name is empty");
            return Result.success(skuCategoryService.updateCategory(category));
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    @SaveLog("删除商品类目")
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam int id){
        return Result.success(skuCategoryService.deleteCategory(id));
    }

}
